
#include "sdicapture.h"


static int xioctl(int fh, int request, void *arg)
{
        int r;
        do {
                r = ioctl(fh, request, arg);
        } while (-1 == r && EINTR == errno);
        return r;
}



void SdiCatprue::init_rga()
{
    printf("init rga\n");
    cap_width = 1920;
    cap_height = 1080;
    cap_format = RK_FORMAT_BGR_888;

    resize_width = 1440;
    resize_height = 1080;
    resize_format = RK_FORMAT_BGR_888;

    video_width = 1920;
    video_height = 1080;
    video_format = RK_FORMAT_RGB_888;

    cap_buf_size = cap_width * cap_height * get_bpp_from_format(cap_format);
    video_buf_size = video_width * video_height * get_bpp_from_format(video_format);
    resize_buf_size = 1440 * 1080 * get_bpp_from_format(resize_format);
    printf("%d %d \n",cap_buf_size,video_buf_size);
}



void SdiCatprue::init_display_buf()
{
    int ret = 0;
    int i;
        int  n1024x768len = 1024*768*3;
    for(i = 0; i < BUFFER_COUNT; i++) {
        ret = dma_buf_alloc(DMA_HEAP_UNCACHE_PATH, cap_buf_size, &cap_dma_fd[i], (void **)&cap_buf[i]);
        if (ret < 0) {
            printf("alloc cap_buf dma_heap buffer failed!\n");
        return;
        }

        cap_handle[i] = importbuffer_fd(cap_dma_fd[i], cap_buf_size);

         if(cap_handle[i] == 0) {
                 printf("import cap_handle error!\r");
                 goto free_buf;
       }
        printf("cam_dma_fd[%d] = %d\n",i,cap_dma_fd[i]);
        src[i] = wrapbuffer_handle(cap_handle[i], cap_width, cap_height, cap_format);
    }




    ret = dma_buf_alloc(DMA_HEAP_UNCACHE_PATH, resize_buf_size, &resize1440x1080_fd, (void **)&resize1440x1080_buf);
    if (ret < 0) {
        printf("alloc video dma_heap buffer failed!\n");
        return;
    }

    resize1440x1080_handle = importbuffer_fd(resize1440x1080_fd, resize_buf_size);
    if (resize1440x1080_handle == 0) {
        printf("import video_handle error!\n");
        goto free_buf;
    }

    resize1440x1080 = wrapbuffer_handle(resize1440x1080_handle, 1440, 1080, resize_format);



    ret = dma_buf_alloc(DMA_HEAP_UNCACHE_PATH, n1024x768len, &resize1080x768_fd, (void **)&resize1024x768_buf);
    if (ret < 0) {
        printf("alloc video dma_heap buffer failed!\n");
        return;
    }

    resize1024x768_handle = importbuffer_fd(resize1080x768_fd, n1024x768len);
    if (resize1024x768_handle == 0) {
        printf("import video_handle error!\n");
        goto free_buf;
    }
    resize1080x768 = wrapbuffer_handle(resize1024x768_handle, 1024, 768, RK_FORMAT_BGR_888);

    return;

free_buf:
    for(i = 0; i < BUFFER_COUNT; i++)
        dma_buf_free(cap_buf_size, &cap_dma_fd[i], cap_buf);


    dma_buf_free(resize_buf_size, &resize1440x1080_fd, resize1440x1080_buf);
    dma_buf_free(n1024x768len, &resize1080x768_fd, resize1024x768_buf);
}



void SdiCatprue::init_mmap(void)
{
    int n_buffers = 0;
    struct v4l2_requestbuffers req;

    CLEAR(req);

    req.count = BUFFER_COUNT;
    req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    req.memory = V4L2_MEMORY_DMABUF;

    if (-1 == xioctl(fd, VIDIOC_REQBUFS, &req)) {
        printf("reqbuf err\n");
        return;
    }

    if (req.count !=  BUFFER_COUNT) {
        printf("buf not exp\n");
        return;
    }
    for (n_buffers = 0; n_buffers < req.count; ++n_buffers) {
        struct v4l2_buffer buf;
        struct v4l2_plane planes[FMT_NUM_PLANES];
        CLEAR(buf);
        CLEAR(planes);

        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
        buf.memory = V4L2_MEMORY_DMABUF;
        buf.index = n_buffers;

        buf.m.planes = planes;
        buf.length = FMT_NUM_PLANES;

        if (-1 == xioctl(fd, VIDIOC_QUERYBUF, &buf))
                printf("VIDIOC_QUERYBUF err\n");

        buf.m.planes[0].m.fd = cap_dma_fd[n_buffers];
        buf.m.planes[0].length = cap_width * cap_height * 3;
    //buf.m.fd = cap_dma_fd[n_buffers];
        if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
            printf("qbuf err\n");

    }
}

void  SdiCatprue::init_device(void)
{
    struct v4l2_capability cap;
    struct v4l2_format fmt;

    init_rga();

    if (-1 == xioctl(fd, VIDIOC_QUERYCAP, &cap)) {
        printf("is no V4L2 devicen\n");
        return;
    }

    if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) &&
            !(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE_MPLANE)) {
            printf("no support cap\n");
            return;
    }

    if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
            printf("no support stream\n");
            return;
    }

    CLEAR(fmt);
    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    fmt.fmt.pix.width = cap_width;
    fmt.fmt.pix.height = cap_height;
    fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24;
    fmt.fmt.pix.field = V4L2_FIELD_NONE;

    if (-1 == xioctl(fd, VIDIOC_S_FMT, &fmt)) {
            printf("no support fmt\n");
            return;
    }



    init_display_buf();

    init_mmap();
}



int SdiCatprue::read_frame(stVFrame*  pFrame)
{
    struct v4l2_buffer buf;
    struct v4l2_plane planes[FMT_NUM_PLANES];
    int i, bytesused;

    CLEAR(buf);
    CLEAR(planes);

    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    buf.memory = V4L2_MEMORY_DMABUF;
    buf.m.planes = planes;
    buf.length = FMT_NUM_PLANES;

    if (-1 == xioctl(fd, VIDIOC_DQBUF, &buf))
        printf("err dqbuf\n");


    i = buf.index;

    bytesused = buf.bytesused;


    int ret, col;

    im_rect  croprect;
    croprect.x = 428;
    croprect.y = 156;
    croprect.width = 1024;
    croprect.height = 768;

   // QImage visiImg = QImage((uchar *)cap_buf[i],1920, 1080, QImage::Format_RGB888);
   // visiImg.save("org.png");


    ret = imcrop(src[i], resize1080x768, croprect);

   // QImage img1024x768 = QImage((uchar *)resize1024x768_buf,1024, 768, QImage::Format_RGB888);
   // img1024x768.save("1024.png");

    ret = imresize(resize1080x768,resize1440x1080,0,0);

   // QImage img1440 = QImage((uchar *)resize1440x1080_buf,1440, 1080, QImage::Format_RGB888);
    //img1440.save("1440.png");

    for(i= 0; i<1080; i++)
    {//all mov 1076 line
        memcpy(pFrame->ucData+  1920*(i)*3 + 240*3,  resize1440x1080_buf + i*1440*3 , 1440*3);
    }

    //QImage outImg = QImage((uchar *)video_buf,1920, 1080, QImage::Format_RGB888);

    //outImg.save("out.png");
   //  outImg.save("out.png");
   //QImage img = QImage("/root/a1.png");

   // img = img.convertToFormat(QImage::Format_RGB888);

   // memcpy(video_buf,img.bits(),1920*1080*3);

   // drm_render(video_buf, 24,
   //               1920, 1080, 1920*3);


    //buf.m.planes[0].m.fd = cap_dma_fd[n_buffers];
    //buf.m.planes[0].length = cap_width * cap_height * 3;
    if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
        printf("err qbuf\n");

    return 1;
}


SdiCatprue::SdiCatprue(QObject *parent )
{

   m_parent = parent;



   m_nFps = 0;
   m_nFps_tv = 0;
   m_nFps_ir = 0;
   m_nFrameCnt = 0;
   m_ThreadRun = true;

   m_nSeq = 0;
   memset(&m_VFrame,0,sizeof(stVFrame)*MAX_FRAME_BUFF_CNT);

}









SdiCatprue::~SdiCatprue()
{
    int i,k;

    for(i = 0; i < BUFFER_COUNT; i++)
        dma_buf_free(cap_buf_size, &cap_dma_fd[i], cap_buf);


    dma_buf_free(resize_buf_size, &resize1440x1080_fd, resize1440x1080_buf);

    dma_buf_free(1024*768*3, &resize1080x768_fd, resize1024x768_buf);

    if(fd > 0)
    {
       close(fd);
    }
}


void SdiCatprue::run()
{


    int nRes = 0;
    fd = open("/dev/video0", O_RDWR /* required */ /*| O_NONBLOCK*/, 0);

   if (-1 == fd) {
       printf("open video err\n");
       return;
   }

   init_device();
   enum v4l2_buf_type type;

   type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
   if (-1 == xioctl(fd, VIDIOC_STREAMON, &type))
   {
       printf("stream on err\n");
       return;
   }

   printf("start succ\n");

    while(m_ThreadRun)
    {

        nRes =  SelectGetFrame();

    }

}





int SdiCatprue::SelectGetFrame()
{
    fd_set fds;
    struct timeval tv;
    int r;
    int  fd_max = 0;



    FD_ZERO(&fds);



    FD_SET(fd, &fds);
    if(fd > fd_max)
    {
        fd_max = fd;
    }

    // Timeout
    tv.tv_sec = 2;
    tv.tv_usec = 0;

    r = select(fd_max + 1, &fds, NULL, NULL, &tv);
    if (-1 == r) {
        if (EINTR == errno)
            return -1;

    }

    if (0 == r)
    {
         return -1;
    }


    if (FD_ISSET( fd, &fds ))
    {

        read_frame(&m_VFrame[m_nSeq]);

        emit ProcFrame(&m_VFrame[m_nSeq]);

        m_nSeq++;

        m_nSeq = m_nSeq%MAX_FRAME_BUFF_CNT;

        m_nFps++;

    }
   return 0;

}
void SdiCatprue::Stop()
{
   m_ThreadRun = 0;
}



